//
//  HMOAuthViewController.swift
//  Weibo
//
//  Created by ZhuDong on 16/5/22.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import SVProgressHUD

class HMOAuthViewController: UIViewController {
    
    private let webView = UIWebView()
    
    override func loadView() {
        view = webView
        webView.delegate = self
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setNav()
        let urlStr = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
//        print(urlStr)
        let url = NSURL(string: urlStr)!
        webView.loadRequest(NSURLRequest(URL: url))
        
    }
    func setNav(){
        let leftBtn = UIBarButtonItem(title: "关闭", imageName: nil, target: self, action: #selector(leftBtnClick))
        let rightBtn = UIBarButtonItem(title: "测试账户", imageName: nil, target: self, action: #selector(rightBtnClick))
        navigationItem.leftBarButtonItem = leftBtn
        navigationItem.rightBarButtonItem = rightBtn
    }
    
   
    
    @objc func leftBtnClick(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    @objc func rightBtnClick(){
       //调用js代码
        let jsString = "document.getElementById('userId').value = 'zhudongpan@sina.com', document.getElementById('passwd').value = '814zhu418?'"
        webView.stringByEvaluatingJavaScriptFromString(jsString)
        
    }
    deinit{
        print("切换根控制器时,销毁了")
    }
    

}

extension HMOAuthViewController: UIWebViewDelegate {
    
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool{
        let urlStr = request.URL?.absoluteString
        let successFlag = "code="
        
        if ((urlStr?.containsString(successFlag))!) {
            let range = (urlStr?.rangeOfString(successFlag))!
            let code = urlStr?.substringFromIndex(range.endIndex)
//            print(code)
            HMUserAccountViewModel.shareAccountViewModel.loadAccessToken(code!, finish: { (isSuccess) in
                if(!isSuccess){
                    SVProgressHUD.showErrorWithStatus("网络繁忙")
                    return
                }

                NSNotificationCenter.defaultCenter().postNotificationName(switchRootViewController, object: "welcome")
            })
           
            return false
        }
        
       return true
    }
    func webViewDidStartLoad(webView: UIWebView){
        SVProgressHUD.show()
    }

    func webViewDidFinishLoad(webView: UIWebView){
        SVProgressHUD.dismiss()
    }
}
